// pages/me/me.js
import { compareVersion } from "../../utils/util";
import { toast } from "../../utils/modal"
import { commonApi, storeApi } from '../../api/index';
import { paySuccess, wxPay } from "../../utils/wxPayment";
// 获取app
var app = getApp();
Page({
  data: {
    filesHost: app.globalData.filesHost,
    userInfo: {},
    userData: {
      avatar: '',
      nickname: ''
    },
    receiver_phone: "",
    showInfoBtn: true, //是否更新头像
    showAuth: false, // 授权弹窗
    isVIP: 0,
    vipPrice: 1990, //会员价
    rightsList: [
      { name: '立减20元' },
      { name: '染发85折' },
      { name: '生日6折' },
    ],
    buttonClicked: true,
    clickRepeatTimer: null,
    showPopup: false,
  },
  async getUserInfo() {
    try {
      let res = await commonApi.getUserInfo()
      this.setData({
        userInfo: res,
        userData: {
          avatar: res.avatar || '',
          nickname: res.nickname,
        },
        receiver_phone: res.phone ? res.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : '', // 手机号脱敏
        isVIP: Number(res.is_vip),
        showInfoBtn: res.avatar === '' ? true : false
      })
      console.log('showInfoBtn', this.data.showInfoBtn)
    } catch (err) {
       console.log('err', err)
     }
  },
  async getVipPrice() {
    try {
      let res = res = await storeApi.getVipPrice()
      this.setData({
        vipPrice: res.final_amount,
      })
    } catch (err) {
       console.log('err', err)
     }
  },
  showAuthPopup() {
    const SDKVersion = app.globalData.systeminfo.SDKVersion
    if (compareVersion(SDKVersion, '2.21.2') >= 0) {
      this.setData({
        showAuth: true,
      })
    } else {
      toast("当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。")
    }
  },
  cancleAuth() {
    this.setData({
      showAuth: false,
    })
  },
  // 输入框
  changeInput(event) {
    let value = event.detail.value;
    this.setData({
      userData: {
        nickname: value,
        avatar: this.data.userData.avatar,
      }
    });
  },
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    this.uploadFile(avatarUrl)
  },
  async uploadFile(filePath) {
    let fileUrl = ''
    let ossParams = await commonApi.getPostObjectParams();
    // console.log(ossParams);
    // 开发者工具
    // http://tmp/wBYdNhh625FT4f4cb4c323564385b9907d5f645aeaaf.png
    let substringlen = 11;
    if (filePath.indexOf("wxfile://") > -1) {
      // 微信本地文件
      // wxfile://tmp_61d7f2811d26513b2a6b9232ad41ded9.jpg
      substringlen = 9;
    }
    let key = `ranstore/avatar/image/${filePath.substring(substringlen)}`;
    wx.uploadFile({
      url: `https://files.iranboss.com`, // 开发者服务器的URL。
      filePath: filePath,
      name: "file", // 必须填file。
      header: {
        "Content-Type": "multipart/form-data",
      },
      formData: {
        key,
        ...ossParams
      },
      success: async (res) => {
        if (res.statusCode === 204) {
          console.log("上传成功");
          console.log(res);
          fileUrl = key

          this.setData({
            userData: {
              ...this.data.userData,
              avatar: fileUrl,
            }
          })
        } else {
          toast('获取头像异常')
        }
      },
      fail: async (err) => {
        console.log(err);
      },
    });
  },
  highUpdateUser() {
    // console.log(this.data.userData)
    const { nickname, avatar } = this.data.userData
    if (nickname.length === 0) return toast("请输入昵称")
    this.updateUserInfo(nickname, avatar)
  },
  async updateUserInfo(nickname, avatar) {
    this.setData({
      showAuth: false,
    });
    await commonApi.updateUserInfo({
      nickname,
      avatar
    });
    this.getUserInfo();
  },
  async createRanstoreVipOrder() {
    try {
      if(this.data.isVIP){
        wx.navigateTo({
          url: `/pages/book-step/book-step`,
        });
        return
      }
      let self = this
      self.setData({
        buttonClicked: false
      })
      wx.showLoading({
        title: '充值中',
      })
      const resp = await storeApi.createRanstoreVipOrder({
        amount: self.data.vipPrice, // 产品金额（分） 会员19.9元
        scene: 11, // 场景值写死（11
        product_name: "染博士染发会员卡", // 商品名称这里写死
      });
      console.log(resp)
      const payParam = { ...resp, order_type: 'vip' }
      console.log(payParam)
      wxPay(payParam , (res)=>{
        console.log('callbackSuc', res)
        this.getUserInfo()
      }, (err)=>{
        console.log('callBackFail', err)
        this.getUserInfo()
      });
      wx.hideLoading();
      self.data.clickRepeatTimer = setTimeout(function () {
        self.setData({
          buttonClicked: true
        })
      }, 1000)
    } catch (e) { }
  },
  goCouponList() {
    // sendEvent(mineEvents.clickMyCoupon);
    wx.navigateTo({
      url: '/couponPack/pages/couponList/couponList'
    })
  },
  goOrder() {
    wx.navigateTo({
      url: "/pages/order/order",
    });
  },
  goCustomer(){
     this.setData({
      showPopup: true
    })
    // 跳企微
    // wx.openCustomerServiceChat({
    //   extInfo: { url: 'https://work.weixin.qq.com/kfid/kfc23c9fdd2b97833a9' },
    //   corpId: 'ww850bee02dd3631a9',
    //   success(res) {
    //     console.log(res);
    //   },
    //   fail(err) {
    //     console.log(err);
    //   },
    // });
    // 跳公众号
    // let url = "https://mp.weixin.qq.com/s/G-K0wNlW451TVYwSCm8DvQ"
    // wx.navigateTo({
    //   url: `/pages/webView/webView?url=${encodeURIComponent(url)}`
    // });
  },
  goFiles(){
    toast("马上开放，敬请期待")
  },
  onClosePopup(){
    this.setData({
      showPopup: false
    })
  },
  async onLoad(options) {
    this.getUserInfo()
    this.getVipPrice()
  },
  onReady() { },
  onShow() { },
  onHide() { },

  onUnload() { },
  onPullDownRefresh() { },
  onReachBottom() { },
  onShareAppMessage() { 
    return {
      title: '频繁染白发，就找染博士',
      imageUrl:
        'https://ranboss.oss-cn-beijing.aliyuncs.com/ranstore/share.png',
    };
  },
});
